//
//  XSNetworkTools.swift
//  Swift网络工具类
//
//  Created by XISHAN on 16/3/4.
//  Copyright © 2016年 XISHAN. All rights reserved.
//

import UIKit
import AFNetworking

enum XSRequestMethod:String{
    case GET = "GET"
    case POST = "POST"
}

class XSNetworkTools: AFHTTPSessionManager {

    typealias XSRequestCallBack = (responseObjc:[String :AnyObject]?,error :NSError?) -> ()
    
    static let sharedXSNeworkTool : XSNetworkTools = {
        
        let tools = XSNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    func request(requestMethod:XSRequestMethod,urlString:String,parameters:AnyObject?,callBack: XSRequestCallBack){
        
        //成功闭包
        let success = {(dataTask:NSURLSessionDataTask,responseObjc:AnyObject?) -> () in
            
            guard let responseDict = responseObjc as? [String :AnyObject]? else{
                callBack(responseObjc: nil, error: NSError(domain: "XiShan", code: 6688, userInfo: ["Information":"返回的数据不是字典或者数组,请调试"]))
                return
            }
            callBack(responseObjc: responseDict, error: nil)
        }

        //失败闭包
        let failure = {(dataTask:NSURLSessionDataTask?,error:NSError) -> () in
            callBack(responseObjc: nil, error:error )
            
        }
        
        if requestMethod == .GET{
            
            self.GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            self.POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
}
